#ifndef __log_hpp__
#define __log_hpp__

#include <iostream>
#include <string>
#include <filesystem>
#include <fstream>
#include <unistd.h>
#include <sstream>
#include <memory>
#include <ctime>
#include "Mutex.hpp"
namespace LogModule
{
    using namespace Mutexmodule;
    // 对于输出的刷新我们使用策略模式，所谓策略模式就是利用c++的多态特性，我们想让数据向什么地方刷新就将指针指向某一个类
    class Logstrategy // 刷新策略基类，作为一个基类
    {
    public:
        ~Logstrategy() = default;
        virtual void Synclog(const std::string &mes) = 0; // 虚基函数，以后用来被派生类中的函数覆盖
    };

    // 向显示器打印日志的子类
    class ConsoleLogstrategy : public Logstrategy
    {
    private:
        Mutex _mutex;

    public:
        ConsoleLogstrategy() {}
        void Synclog(const std::string &mes) override // 函数重写
        {
            Lockguard lockguard(_mutex);
            std::cout << mes << "\r\n";
        }
        ~ConsoleLogstrategy() {}
    };

    const std::string defaultpath = "./log";
    const std::string defaultfile = "my.log";
    // 向文件打印日志的子类
    class FileLogstrategy : public Logstrategy
    {
    private:
        std::string _path; // 文件路径
        std::string _file; // 文件名
        Mutex _mutex;

    public:
        FileLogstrategy(const std::string &path = defaultpath, const std::string &file = defaultfile) : _path(path), _file(file)
        {
            Lockguard lockguard(_mutex);
            if (std::filesystem::exists(_path)) // 当前路径是否存在
                return;
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }
        void Synclog(const std::string &mes) override
        {
            Lockguard lockguard(_mutex);
            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _file;
            std::ofstream out(filename, std::ios::app); // 以追加写入的方式打开文件流
            if (!out.is_open())
                return;
            out << mes << "\r\n";
            out.close();
        }
        ~FileLogstrategy() {}
    };
    
    // 生成日志等级
    enum class Loglevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string level_to_string(Loglevel level)
    {
        switch(level)
        {
            case Loglevel::DEBUG:
                return "DEBUG";
            case Loglevel::ERROR:
                return "ERROR";
            case Loglevel::FATAL:
                return "FATAL";
            case Loglevel::INFO:
                return "INFO";
            case Loglevel::WARNING:
                return "WARNING";
            default:
                return "UNKNOWN";
        }
    }

    // 获得时间
    std::string GetTimestamp()
    {
        time_t curr =time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr,&curr_tm);
        std::stringstream ss;
        ss<<(curr_tm.tm_year+1900)<<"."<<(curr_tm.tm_mon+1)<<"."<<curr_tm.tm_mday<<" "<<curr_tm.tm_hour<<":"<<curr_tm.tm_min<<":"<<curr_tm.tm_sec;
        return ss.str();
    }


    class Logger // 日志类，1.生成日志 2.根据不同的策略完成刷新
    {
    private:
        std::unique_ptr<Logstrategy> _flush_strateggy;
    public:
        Logger() { enableconsolelogstrategy();}
        void enablefilelogstrategy()
        {
            _flush_strateggy = std::make_unique<FileLogstrategy>("./Log","file");//在这里修改你所需要的日志地址和文件名
        }
        void enableconsolelogstrategy()
        {
            _flush_strateggy = std::make_unique<ConsoleLogstrategy>();
        }
        class logmessage // 表示一条日志
        {
        private:
            std::string _time;
            Loglevel _level;
            pid_t _pid;
            std::string _filename;
            int _line;
            std::string _log_info;
            Logger& _logger;//内部类可以访问外部类的私有成员
        public:
            logmessage(Loglevel level,const std::string &filename,int line,Logger& logger):
            _time(GetTimestamp()),
            _level(level),
            _pid(getpid()),
            _filename(filename),
            _line(line),
            _logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _time << "] "
                   << "[" << level_to_string(_level) << "] "
                   << "[" << _pid << "] "
                   << "[" << _filename << " : " << _line << "] - ";
            _log_info = ss.str();
            }
            template<class t>
            logmessage& operator<<(const t &info)
            {
                std::stringstream ss;
                ss<<info;
                _log_info+=ss.str();
                return *this;
            }
            ~logmessage()
            {
                if(_logger._flush_strateggy)
                    _logger._flush_strateggy->Synclog(_log_info);
            }
        };
        logmessage operator()(Loglevel level,const std::string &filename,int line)
        {
            return logmessage(level,filename,line,*this);
        }
        ~Logger() {}
    };
    Logger logger;
    //使用宏来简化调用操作
    #define LOG(level) logger(level,__FILE__,__LINE__)
    #define Enable_file_logstrategy() logger.enablefilelogstrategy()
    #define Enable_console_logstrategy() logger.enableconsolelogstrategy()

}

#endif
